package com.imooc.distributedlock.controller;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author Fxz
 * @version 1.0
 * @date 2022-01-30 14:13
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class LockController {

    private final RedissonClient redissonClient;

    @SneakyThrows
    @GetMapping("/lock")
    public void lock() {
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        TimeUnit.SECONDS.sleep(3);
        lock.unlock();
        log.info("解锁了...");
    }

    @SneakyThrows
    @GetMapping("/tryLock")
    public void tryLock() {
        RLock lock = redissonClient.getLock("lock");
        boolean tryLock = lock.tryLock();
        if(tryLock){
            TimeUnit.SECONDS.sleep(3);
            lock.unlock();
            log.info("解锁了...");
        }else{
            log.info("很遗憾!");
        }

    }

}
